<?php


namespace App\Admin\Controllers;


use App\Admin\Actions\ProductBatch\Circulation;
use App\Admin\Actions\ProductBatch\Loss;
use App\Admin\Actions\ProductBatch\MarketSale;
use App\Admin\Actions\ProductBatch\View;
use App\Models\CustomerModel;
use App\Models\ProductModel;
use App\Models\ProductsBatchModel;
use App\Models\ProductsSaleModel;
use App\Models\SpaceModel;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;

class SaleController extends AdminController
{
    use HasResourceActions;

    protected $title = '批次';

    public function index(Content $content)
    {
        return $content
            ->header(trans('admin.sale'))
            ->description(trans('admin.list'))
            ->body($this->grid()->render());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ProductsBatchModel());

        $grid->model()->orderBy('batch_id', 'desc');
//        $grid->model()->where('status', 1);

        $grid->column('product.product_name', '商品名');
        $grid->column('product.variety_name', '产品种类');
        $grid->column('source_code', '溯源码')->copyable();
        $grid->column('auth_type', '认证类型')->display(function ($data) {
            $str = '';
            $arr = explode(',', $data);
            foreach ($arr as $k => $v) {

                if ($k > 0) {
                    $str .= ',' . ProductsBatchModel::MAP_AUTH[$v];
                } else {
                    $str .= ProductsBatchModel::MAP_AUTH[$v];
                }
            }
            return $str;
        });
        $grid->column('stock', '库存');
        $grid->column('sale_number', '已售')->modal('销售记录', function ($model) {


            $sale = $model->productSale()->take(100)->orderBy('sale_id', 'desc')->get()->map(function ($sale) {
                return $sale->only(['sale_id', 'sale_num', 'sale_type', 'code', 'customer_id', 'created_at']);
            });

            return new Table(['ID', '售出数量', '售出类型', '入市追溯码', '客户id', '销售时间'], $sale->toArray());
        });


        $grid->column('source', '产品来源')->using(ProductsBatchModel::MAP_SOURCE);

        $grid->column('quality_result', '质检情况')->using(ProductsBatchModel::MAP_QUALITY);
        $grid->column('receive_time', '收获时间')->sortable();

        $grid->disableCreateButton();
        $grid->actions(function ($action) {
            $action->disableView();
            $action->disableDelete();
            $action->disableEdit();
            $action->add(new Circulation());
            $action->add(new MarketSale());
        });

        return $grid;
    }

}
